$(function () {
    // 动态显示所有角色
    $.get('/kobe/role.do', requestRoles);
    // 获取管理员id发给后台
    var urlParm = decodeURI(window.location.href.split('?')[1]);
    aid = urlParm.split('=')[1];
    var url = '/kobe/modifyFindAdmin.do?adminId=' + aid;
    $.get(url, requestFindAdmin);
});

function requestFindAdmin(resp) {
    $('#name').val(resp.adminInfo.name);
    $('#adminCode').val(resp.adminInfo.adminCode);
    $('#telephone').val(resp.adminInfo.telephone);
    $('#email').val(resp.adminInfo.email);
    // 这里改你数据库读出的
    var arr = resp.roleIds;
    // 前后加限定符
    arr = ',' + arr + ',';
    //这里改你checkbox的name值
    var ulli = document.getElementsByName('ulli');
    for (var i = 0; i < ulli.length; i++) {
        if (arr.indexOf(',' + ulli[i].value + ',') != -1) ulli[i].checked = true;
    }
}

// 动态显示所有角色
function requestRoles(resp) {
    var ul = $('#ul');
    ul.empty();
    for (var item of resp) {
        var li = $('<li></li>').text(item.name);
        var inputRole = $('<input name="ulli" type="checkbox"/>');
        inputRole.val(item.roleId);
        ul.append(li);
        li.append(inputRole);
    }
}


//保存成功的提示消息
function showResult() {
    var adminInfo = {
        'name': $('#name').val(),
        'adminCode': $('#adminCode').val(),
        'telephone': $('#telephone').val(),
        'email': $('#email').val()
    };
    var arr = [];
    $('input[type="checkbox"]:checked').each(function () {
        arr.push($(this).val());
    });
    var adminParams = {
        'adminInfo': adminInfo,
        'roleIds': arr
    };

    var settiings = {
        url: '/kobe/modifyAdmin.do?adminId=' + aid,
        method: 'post',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(adminParams)
    };
    $.ajax(settiings).done(requestModifyAdmin);
}

function requestModifyAdmin(resp) {
    if (resp) {
        $('#save_result_info').attr('class', 'save_success').text('保存成功!');
        showResultDiv(true);
        window.setTimeout("showResultDiv(false);", 3000);
    } else {
        $('#save_result_info').attr('class', 'save_fail').text('保存失败!');
        showResultDiv(true);
        window.setTimeout("showResultDiv(false);", 3000);
    }
}

function showResultDiv(flag) {
    var divResult = document.getElementById("save_result_info");
    if (flag)
        divResult.style.display = "block";
    else
        divResult.style.display = "none";
}